<template>
  <el-form label-position="top" :rules="rules" ref="form" :model="form" class="padding-b img-parent">
    <el-form-item :label="label" prop="busFile">
      <el-button :class="btnStyle.icon ? 'iconfont icon-fujian': ''" :id="btnId" :disabled="disabled" :type="btnStyle.type" :size="btnStyle.size">{{btnStyle.text}}</el-button>
      <span style="font-size:12px;margin-left:20px;">{{$t('business.fileMoreThanTenMb')}}</span>
      <div class="process-ui" v-if="progressUi.show">
        <span>{{progressUi.fileName}}</span>
        <el-progress :text-inside="true" :stroke-width="18" :percentage="progressUi.percent" :status="progressUi.type"></el-progress>
      </div>
      <br>
      <div v-for="(file, index) in form.busFile" v-if="form.busFile.length" class="file-item">
        <globalPopup :url="common.getUrl(file,{useAttach: true})"
                     :key="common.getUrl(file,{useAttach: true})"
                     @showBigImage="showBigImage"
                     @deleteFile="deleteFile"
                     :name="file.name"
                     :currObj="{url: common.getUrl(file,{useAttach: true}), id: file.id, index: index, disabled: disabled, showDelBtn: true}"
                     :srcUrl="common.getUrl(file,{useAttach: true})" :imgObj="[]"></globalPopup>
      </div>
      <input type="hidden" v-model.trim="form.busFile"/>
    </el-form-item>
    <!--<big-image :imgInfo="bigImage" @closeImageDialog="closeBigImage"></big-image>-->
  </el-form>
</template>
<script>
  import {uploadTo7moorDomain, qiniu7moorDomain} from '@/utils/qiniuUtils'
  import {getCurrentDate, deepClone} from '@/utils/m7Utils'
  import globalPopup from '../../../../ui-modules/affix/globalPopup.vue'
  import * as uuid from 'uuid'
  import { common } from '@/utils/cosUrl'
  import {checkform} from '@/utils/validate'
  export default {
    name: 'Bfile',
    props: {
      label: String,
      default: {
        type: Array,
        default: function () {
          return []
        }
      },
      disabled: {type: String | Boolean, default: false},
      id: String,
      require: String,
      random: {type: Number, default: 0},
      btnStyle: {
        type: Object,
        default: function () {
          return {
            text: '',
            type: 'text',
            size: '',
            icon: true
          }
        }
      }
    },
    components: {
      globalPopup
    },
    data () {
      let validate1 = (rule, value, callback) => {
        if (this.require === 'required' && (value === undefined || value.length === 0)) {
          callback(new Error(this.$t('validate.required')))
        } else {
          callback()
        }
      }
      return {
        dataType2: ['mp3', 'wav', 'ogg'],
        dataType1: ['txt', 'TXT'],
        dataType: ['pdf', 'PDF', 'plain'],
        bigImage: {
          bigImageShow: false,
          url: ''
        },
        name: 'file',
        btnId: 'btn' + uuid.v1(),
        form: {
          busFile: deepClone(this.default)
        },
        rules: {
          busFile: [
            {validator: validate1, required: this.require === 'required', trigger: 'blur'}
          ]
        },
        qiniu7moorDomain: qiniu7moorDomain,
        progressUi: {
          show: false,
          percent: 0,
          type: 'success',
          fileName: '',
          disabled: false
        },
        uploader: '',
        common
      }
    },
    watch: {
      random: {
        deep: true,
        handler: function (newV, oldV) {
          let value = this.form.busFile
          let self = this
          if (this.require === 'required') {
            this.$refs.form.validate((valid) => {
              if (valid) {
              } else {
                value = false
              }
            })
          }
          self.$emit('tellme', {[self.id]: value})
        }
      },
      'form.busFile' () {
        this.$emit('blurEvent', this.submit(true))
      }
    },
    computed: {
      attachmentMaxSize () {
        return this.$store.state.attachmentMaxSize
      }
    },
    methods: {
      submit (noCheck) {
        // noCheck为true 不进行校验
        let obj = {}
        if (noCheck) {
          obj.success = true
        } else {
          this.$refs.form.validate((valid) => {
            obj.success = valid
          })
        }
        if (obj.success) {
          obj.data = {[this.id]: this.form.busFile}
        }
        return obj
      },
      checkImg (value) {
        if (checkform(value, 'Img')) {
          return false
        } else {
          return true
        }
      },
      closeBigImage () {
        this.bigImage.bigImageShow = false
        this.bigImage.url = ''
      },
      showBigImage (data) {
        this.$emit('showBigImg', data.url)
      },
      rulesValue () {
        if (this.require === 'required') {
          return 'busFile'
        } else {
          return ''
        }
      },
      initUploadBusFile (ev) {
        let account = this.$store.state.session.user.account
        let that = this
        let filters = {}
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          that.progressUi.show = true
          that.progressUi.percent = 0
          that.progressUi.fileName = file.name
          console.log('beforeUpload')
        }
        let uploadProgress = function (up, file) {
          that.progressUi.percent = file.percent
          console.log('uploadProgress')
        }
        let uploadComplete = function () {
          that.progressUi.show = false
          console.log('uploadComplete')
        }
        let fileUploaded = function (up, file, info) {
          let res = JSON.parse(info || '{}')
          const id = that.$store.state.isUseQiniu ? res.key : (that.$store.state.fileDomain.cos7moorTestDomain + (file.fileKey || up.multipart_params.key))
          let obj = {
            name: file.name,
            type: file.type,
            id,
          }
          that.form.busFile.push(obj)
          if (that.require === 'required') {
            that.$refs.form.validate((valid) => {
            })
          }
        }
        let error = function (up, err, errTip) {
          if (err.code === -600) {
            that.$message.error(that.$t('business.attachmentMaxDescription20'))
          }
          that.progressUi.show = false
          console.log('uploadError ' + errTip)
        }
        let key = function (up, file) {
          let date = getCurrentDate()
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          // let fileSuffix = ''
          // if (fileName) {
          //   fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
          // }
          const cmpKey = that.$store.state.isUseQiniu ? 'business' : 'm7-business'
          let key = account + `/${cmpKey}/` + date + '/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        this.uploader = uploadTo7moorDomain(that.$store.state.fileDomain.cos7moorBusinessDomain, this.$store.state.session.user._id, this.btnId, filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key, this.attachmentMaxSize, true, false)
      },
      deleteFile (_data) {
        let fileId = _data.id
        let index = _data.index
        let data = {
          _id: '',
          field: this.id,
          fileId: fileId
        }
        this.$store.dispatch('delBusAttach', data).then((res) => {
          this.form.busFile.splice(index, 1)
        })
      },
      addfile (blob, name) {
        // this.form.busFile.push(obj)
        const key = `${+ new Date()}/image.png`
        blob.fileKey = key
        this.uploader.addFile(blob, name)
      },
      resetForm (data) {
        this.form.busFile = data || []
      }
    },
    beforeDestroy () {
      this.uploader && this.uploader.destroy && this.uploader.destroy()
      this.uploader = null
    },
    mounted () {
      if (!this.disabled) {
        this.initUploadBusFile()
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl";
  .icon-yulan
    padding-left 10px
    color $c-main
    cursor pointer
  .padding-b
    padding-bottom $padding5
  .file-item
    margin-right 20px
    display inline-block  
</style>
